<script setup lang="ts">
import type { FormRules } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'

interface Props {
  data?: Record<string, any> | never | null
  status?: string | never | null
}

const props = withDefaults(defineProps<Props>(), {
  data: null,
  status: 'add'
})

const formRef = ref()

const form = ref<Record<string, any>>({})

const rules = reactive<FormRules>({
  miniMenuName: [{ required: true, message: '菜单名称不能为空!', trigger: 'blur' }],
  miniRouteName: [{ required: true, message: '路由名称不能为空!', trigger: 'blur' }],
  miniMenuUrl: [{ required: true, message: '路由路径不能为空!', trigger: 'blur' }]
})

const types = [
  // {
  //   value: 0,
  //   label: '功能模块'
  // },
  {
    value: 1,
    label: '功能菜单'
  },
  {
    value: 2,
    label: '功能按钮'
  }
]

const initForm = () => {
  form.value['miniMenuType'] = 1
  form.value['useStatus'] = 1
  if (props.data) {
    Object.keys(props.data).forEach((key: string) => {
      form.value[key] = props.data![key]
    })
  }
}

const formatForm = () => {
  const { id, miniMenuName, miniRouteName, miniMenuUrl, miniMenuType, useStatus, parentId } = form.value
  const result: Record<string, any> = {
    miniMenuName,
    miniRouteName,
    miniMenuType,
    useStatus
  }
  // 菜单才有的参数
  if (miniMenuType === 1) {
    result.miniMenuUrl = miniMenuUrl
  }
  if (props.status === 'add') {
    // 添加
    result.parentId = parentId
  } else if (props.status === 'edit') {
    // 更新
    result.menuId = id
  }
  return result
}

const submitForm = () => {
  return new Promise<any>((resolve) => {
    formRef.value.validate((valid: boolean) => {
      let res = null
      if (valid) {
        res = formatForm()
      }
      resolve(res)
    })
  })
}

defineExpose({
  submitForm
})

onMounted(() => {
  initForm()
})
</script>

<template>
  <div class="form-wrapper">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="类型:" prop="miniMenuType">
        <el-select v-model="form.miniMenuType" placeholder="请选择类型">
          <el-option v-for="item in types" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="菜单名称:" prop="miniMenuName">
        <el-input v-model="form.miniMenuName" type="text" placeholder="请输入内容"> </el-input>
      </el-form-item>
      <el-form-item label="路由名称:" prop="miniRouteName">
        <el-input v-model="form.miniRouteName" type="text" placeholder="请输入内容"> </el-input>
      </el-form-item>
      <el-form-item label="路由路径:" prop="miniMenuUrl">
        <el-input v-model="form.miniMenuUrl" type="text" placeholder="请输入内容"> </el-input>
      </el-form-item>
      <el-form-item label="状态:" prop="useStatus">
        <el-switch v-model="form.useStatus" :active-value="1" :inactive-value="0" />
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped></style>
